package usf.gwt.ui.bootstrap.client;

import usf.gwt.ui.bootstrap.client.core.BootstrapWidget;
import usf.gwt.ui.bootstrap.client.core.JqueryUtils;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.InputElement;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;

public abstract class FormControl<T> extends BootstrapWidget implements HasValueChangeHandlers<T> {
	
	public final static String DEFAULT_FORM_CONTROL_STYLE = "form-control";
	
	protected JavaScriptObject changeEvent;
	
	public FormControl() {
		super();
	}
	
	public boolean isEnabled() {
		return JqueryUtils.isFormControlEnabled(getBaseElement());
	}
	public void setEnabled(boolean enabled){
		JqueryUtils.setFormControlEnabled(getBaseElement(), enabled);
	}
	
	public void setName(String name) {
		getBaseElement().setName(name);
	}
	public String getName() {
		return getBaseElement().getName();
	}
	
	public String getValue() {
		return getBaseElement().getValue();
	}
	public void setValue(String value) {
		getBaseElement().setValue(value);
	}
	
	@Override
	protected InputElement getBaseElement() {
		return getElement().cast();
	}
	
	@Override
	public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
		if(changeEvent==null) attachChangeHandler(this);
		return addHandler(handler, ValueChangeEvent.getType());
	}
    public static final native JavaScriptObject attachChangeHandler(final FormControl<?> f) /*-{
		var e = f.@usf.gwt.ui.bootstrap.client.TextBox::getElement()();
		return $wnd.$(e).change(function() {
			f.@usf.gwt.ui.bootstrap.client.FormControl::fireChange(Lcom/google/gwt/dom/client/NativeEvent;)(e);
		});
	}-*/;
    
    protected void fireChange(NativeEvent e) {
    	ValueChangeEvent.fire(this, getChangedValue(e));
    }
    protected abstract T getChangedValue(NativeEvent e);
}
